package it.giuseppetrisciuoglio.lyrics.processor;

import it.giuseppetrisciuoglio.lyrics.persistence.entity.Artista;
import it.giuseppetrisciuoglio.lyrics.persistence.entity.Canzone;
import it.giuseppetrisciuoglio.lyrics.persistence.repository.ArtistaRepository;
import it.giuseppetrisciuoglio.lyrics.persistence.repository.CanzoneRepository;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class FindAllSongsProcessor {

	private final transient Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private CanzoneRepository canzoneRepository;
	
	@Autowired
	private ArtistaRepository artistaRepository;
	
	@Value("${download.lyrics.enabled}")
	private boolean downloadEnabled;
	
	public List<Canzone> process(Exchange exchange){
		log.debug("process(): exchange={}", exchange);
		if (!downloadEnabled){
			log.error("process(): is disabled.");
			return new ArrayList<Canzone>();
		}
		Long artistaId = (Long) exchange.getIn().getHeader("artistaId");
		if (artistaId == null){
			log.error("process(): artistaId è null.");
			throw new RuntimeException();
		}
		Artista artista = artistaRepository.findOne(artistaId);
		List<Canzone> canzoni = canzoneRepository.findByArtistaAndTestoIsNull(artista);
		log.debug("process(): trovate {} canzoni.", canzoni != null ? canzoni.size() : 0);
		return canzoni;
	}
}
